package com.boarsoft.boar.demo.tenant.config;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.boar.demo.tenant.bean.TenantMeta;
import com.boarsoft.config.core.ConfigFileSync;
import com.boarsoft.config.spring.SpringXmlListener;
import com.boarsoft.dao.sharding.group.SimpleMapShardGroup;

public class TenantXmlListener extends SpringXmlListener {
	private final Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	protected ConfigFileSync configFileSync;

	protected SimpleMapShardGroup mapShardGroup;

	@Override
	public boolean onReady(String frp) {
		// 管理员为新创建的租户编写数据源配置文件，提交配置中心，并下发
		// 执行 configFileSync.syncOne(bytes, tenantId, frp); 触发此事件
		if (!super.onReady(frp)) {
			return false;
		}
		String fn = new File(frp).getName();
		String tenantId = fn.substring(0, fn.length() - 4);
		log.info("Receive tenant meta {}", tenantId);
		TenantMeta tm = appCtx.getBean(tenantId, TenantMeta.class);
		mapShardGroup.put(tenantId, tm.getDataSource());
		return true;
	}

	@Override
	public boolean onRemove(String frp) {
		// 管理员删除或禁用租户时
		// 执行 configFileSync.remove(tenantId, frp); 触发此事件
		String fn = new File(frp).getName();
		String tenantId = fn.substring(0, fn.length() - 4);
		log.info("Remove tenant meta {}", tenantId);
		// 移除映射关系
		mapShardGroup.removeDataSource(tenantId);
		// 移除当前tenant的TenantMeta定义
		beanFactory.removeBeanDefinition(tenantId);
		return true;
	}

	public SimpleMapShardGroup getMapShardGroup() {
		return mapShardGroup;
	}

	public void setMapShardGroup(SimpleMapShardGroup mapShardGroup) {
		this.mapShardGroup = mapShardGroup;
	}
}